package aad.storyboard.model;

import aad.storyboard.controller.GUIComposer;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.Log;

public class RotateAnimation extends Animation{

	private int degrees;
	private float intervalMovement;
	private float totalRotated;
	
	public RotateAnimation(int time, int deg, int duration) {
		super(duration,time);
		intervalMovement = (float) this.degrees/intervals;
		this.totalRotated = 0;
	}
	
	

	public RotateAnimation(int deg, int duration) {
		super(duration);
		this.degrees = deg;
		intervalMovement = (float) this.degrees/intervals;
	}
	
	@Override
	public void animate() {
			for(Image obj : this.images){
				Bitmap mBitmap = obj.getBitmap();
				// compute the absolute rotation
		        totalRotated = (intervalMovement) % 360;
		        // precompute some trig functions
		        double radians = Math.toRadians(totalRotated);
		        double sin = Math.abs(Math.sin(radians));
		        double cos = Math.abs(Math.cos(radians));
		        // figure out total width and height of new bitmap
		        double newWidth = mBitmap.getWidth() * cos + mBitmap.getHeight() * sin;
		        double newHeight = mBitmap.getWidth() * sin + mBitmap.getHeight() * cos;
		        // set up matrix
		        Matrix matrix = new Matrix();
		        matrix.reset();
		        matrix.setRotate(totalRotated);
		        // create new bitmap by rotating mBitmap
		        Bitmap rotated = Bitmap.createBitmap(mBitmap, 0, 0,
		                                      (int)Math.ceil(newWidth), (int)Math.ceil(newWidth), matrix, true);
		        obj.setBitmapBuffer(mBitmap);
		        obj.setWidth((float)newWidth);
		        obj.setHeight((float)newHeight);
			}
		
	}

	@Override
	public void undo() {

		for(Image obj : this.images){
			Matrix transMatrix = new Matrix();
			transMatrix.postRotate(-degrees);
			Bitmap origBMap = obj.getBitmapBuffer();
			Bitmap rotatedBitmap = Bitmap.createBitmap(origBMap, 0, 0,obj.getWidth(), obj.getHeight(), transMatrix, true); 
			obj.setBitmapBuffer(rotatedBitmap);
		}
		
	}



	@Override
	public void adjustParameters() {
		this.degrees = Math.round(this.currentDuration * this.intervalMovement);
	}

}
